package com.zhss.demo.curator;

import java.util.ArrayList;
import java.util.List;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class Application {

	public static void main(String[] args) throws Exception {
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
		CuratorFramework client = CuratorFrameworkFactory.newClient(
				"192.168.31.184:2181,192.168.31.207:2181,192.168.31.192:2181",  
				retryPolicy);
		client.start();
		
//		client.create()
//				.creatingParentsIfNeeded()
//				.forPath("/user/dir", "hello world".getBytes());  
//		
//		System.out.println(new String(client.getData().forPath("/my/path")));    
		
//		InterProcessMutex lock = new InterProcessMutex(client, "/locks/lock_01"); 
		
//		InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(
//				client, "/semaphores/semaphore_01", 3); 
//		Lease lease = semaphore.acquire();
//		Thread.sleep(3000); 
//		semaphore.returnLease(lease);  
		
//		InterProcessSemaphoreMutex lock = new InterProcessSemaphoreMutex(
//				client, "/locks/lock_01"); 
		
//		InterProcessReadWriteLock lock = new InterProcessReadWriteLock(
//				client, "/locks/lock_01");
//		lock.writeLock().acquire();
//		lock.readLock().acquire();
//		lock.readLock().release();  
//		lock.writeLock().release(); 
		
		InterProcessLock lock1 = new InterProcessMutex(client, "/locks/lock_01"); 
		InterProcessLock lock2 = new InterProcessMutex(client, "/locks/lock_02");
		InterProcessLock lock3 = new InterProcessMutex(client, "/locks/lock_03"); 
		
		List<InterProcessLock> locks = new ArrayList<InterProcessLock>();
		locks.add(lock1);
		locks.add(lock2);
		locks.add(lock3);
		
		InterProcessMultiLock multiLock = new InterProcessMultiLock(locks);
		multiLock.acquire();
		multiLock.release();
	}
	
}
